package admin

import (
	"fmt"
	"strconv"
	"strings"
	"tcsc/models"
	"tcsc/sword"

	"github.com/astaxie/beego"
)

type Shop struct {
	BaseController
}

func (c *Shop) Get() {
	c.Data["column"] = models.Query(`select id,name from mt_column where type='p' and status=1 and pid=0`)
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	var w []string
	w = append(w, `a.status=1`)
	search := c.GetString("search")
	cid := c.GetString("cid")
	s := c.GetString("s")
	c.Data["cid"] = cid
	c.Data["s"] = s
	if search != "" {
		w = append(w, `a.name like '%`+search+`%'`)
	} else {
		if cid != "" {
			w = append(w, `a.type like '%,`+cid+`,%'`)
		}
		if s != "" {
			w = append(w, `a.style=`+s)
		}
	}
	ws := strings.Join(w, ` and `)
	lt := ` limit ` + page + `,` + num
	ob := ` order by a.addtime desc`
	sql := `select a.*,c.pathname,b.monicker from mt_shop a left join mt_member b on a.uid=b.id left join mt_resources c 
	on a.logo=c.id where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_shop a where ` + ws
	info := models.Query(sql)
	for _, v := range info {
		t := fmt.Sprint(v["type"])
		t = strings.Trim(t, ",")
		if t == "" || t == "<nil>" {
			t = "''"
		}
		v["types"] = models.Query(fmt.Sprintf(`select name from mt_column where id in(%v)`, t))
	}
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/shop/index?search=` + search + `&cid=` + cid + `&s=` + s + `&`
	c.TplName = "admin/shop/index.html"
}

type ShopAE struct {
	BaseController
}

func (c *ShopAE) Get() {
	c.Data["brand"] = models.Query(`select id,name from mt_brand where censoring=1 and status=1`)
	c.Data["cid"] = models.Query(`select id,name from mt_column where type='p' and status=1 and pid=0`)
	province := models.Query(`select * from mt_area where pid=0`)
	c.Data["province"] = province
	id := c.GetString("id")
	imgs := make(map[int]string)
	picnum := make(map[int]string)
	for i := 0; i < 4; i++ {
		imgs[i] = "/static/img/admin/uppic.png"
		picnum[i] = ""
	}
	if id != "" {
		if info := models.Query(`select a.*,b.pathname,c.pathname as gzhpath,d.pathname as apppath,e.pathname as webpath,f.pathname as xapppath
		 from mt_shop a left join mt_resources b on a.logo=b.id left join mt_resources c on a.gzhimg=c.id left join mt_resources d on a.appimg=d.id 
		 left join mt_resources e on a.webimg=e.id left join mt_resources f on a.xappimg=f.id where a.id=` + id); info != nil {
			picture := fmt.Sprint(info[0]["companyimg"])
			if picture != "" && picture != "<nil>" {
				if imgss := models.Query(fmt.Sprintf(`select id,pathname from mt_resources where id in(%v)`, picture)); imgss != nil {
					for k, v := range imgss {
						imgs[k] = fmt.Sprint(v["pathname"])
						picnum[k] = fmt.Sprint(v["id"])
					}
				}
			}
			if shen, ok := info[0]["province"].(string); ok {
				city := models.Query(`select a.* from mt_area a left join mt_area b on a.pid=b.id where b.code=` + shen)
				c.Data["city"] = city
				if shi, ok := info[0]["city"].(string); ok {
					c.Data["area"] = models.Query(`select a.* from mt_area a left join mt_area b on a.pid=b.id where b.code=` + shi)
				} else {
					c.Data["area"] = models.Query(`select a.* from mt_area a left join mt_area b on a.pid=b.id where b.code=` + city[0]["code"].(string))
				}
			} else {
				city := models.Query(`select a.* from mt_area a left join mt_area b on a.pid=b.id where b.code=` + province[0]["code"].(string))
				c.Data["city"] = city
				c.Data["area"] = models.Query(`select a.* from mt_area a left join mt_area b on a.pid=b.id where b.code=` + city[0]["code"].(string))
			}
			c.Data["info"] = info[0]
		} else {
			c.Ctx.Redirect(302, "/admin/shop/index")
		}
	}
	c.Data["imgs"] = imgs
	c.Data["picnum"] = picnum
	c.TplName = "admin/shop/ae.html"
}
func (c *ShopAE) Post() {
	defer c.ServeJSON()
	input := c.Input()
	input.Set("companyimg", strings.Trim(strings.Join(c.GetStrings("companyimg"), ","), ","))
	input.Set("type", ","+strings.Trim(strings.Join(c.GetStrings("type"), ","), ",")+",")
	if input.Get("id") == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
		input.Set("password", sword.ToMD5(input.Get("password")))
	} else {
		shopold := models.Query(`select password from mt_shop where id=` + input.Get("id"))
		password := fmt.Sprint(shopold[0]["password"])
		if password != input.Get("password") {
			input.Set("password", sword.ToMD5(input.Get("password")))
		}
	}
	if res, err := models.Save("mt_shop", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		var r models.Mt_systems_record
		r.Tid = int(res)
		if input.Get("id") == "" {
			r.Way = 2
		} else {
			r.Way = 3
		}
		r.Addtime = sword.Timeget()
		r.Table = 13
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
}

type ShopArea struct {
	BaseController
}

func (c *ShopArea) Get() {
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	lt := ` limit ` + page + `,` + num
	w := ` where a.status=1`
	info := models.Query(`select a.id,a.name,a.addtime,a.status,b.pathname from mt_area_production a 
		left join mt_resources b on a.img=b.id` + lt)
	sql2 := `select count(a.id) as totals from mt_area_production a` + w
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.TplName = "admin/shop/area.html"
}

type ShopAreaAE struct {
	BaseController
}

func (c *ShopAreaAE) Get() {
	id := c.GetString("id")
	shop := models.Query(`select id,name from mt_shop where status=1 and censoring=1`)
	brandclassify := models.Query(`select id,name from mt_brand_classify where status=1`)
	program := models.Query(`select id,name from mt_program where status=1 and gid=` + c.Gid)
	structure := models.Query(`select id,name from mt_goods_struct where status=1`)
	Novice := models.Query(`select id,title as name from mt_novice_join where status=1`)
	maincolumn := models.Query(`select id,name from mt_column where status=1 and level=1`)
	if id != "" {
		info := models.Query(`select a.id,a.name,a.sid,a.img,a.status,a.Dis,a.style,a.brandclassify,a.program,a.structure,a.Novice,a.maincolumn,b.pathname from mt_area_production a
			left join mt_resources b on a.img=b.id
			where a.id=?`, id)
		c.Data["info"] = info[0]
	}
	c.Data["shop"] = shop
	c.Data["brandclassify"] = brandclassify
	c.Data["program"] = program
	c.Data["structure"] = structure
	c.Data["Novice"] = Novice
	c.Data["maincolumn"] = maincolumn
	c.TplName = "admin/shop/area_ae.html"
}

func (c *ShopAreaAE) Post() {
	input := c.Input()
	json := make(map[string]interface{})
	c.Data["json"] = &json
	defer c.ServeJSON()
	if input.Get("id") == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
	}
	sid := strings.Replace(strings.Trim(strings.Join(c.GetStrings("sid"), ","), ","), ",", ",", -1)
	input.Set("sid", sid)
	// bidArr := strings.Split(bid, ",")
	// for _, v := range bidArr {
	// 	classify := models.Query(`select * from mt_brand_classify
	// 		where bid like '`+v+`,%' or bid like '%,`+v+`' or bid like '%,`+v+`,%'`)
	// 	for _, item := range classify {
	// 		id := item["id"].(string)
	// 		bids := fmt.Sprint(item["bid"])
	// 		if bids != "" {
	// 			bidArr := strings.Split(bids, ",")
	// 			isChange := false
	// 			for index, _ := range bidArr {
	// 				if bidArr[index] == v {
	// 					beego.Debug()
	// 					bidArr = append(bidArr[:index], bidArr[index+1:])
	// 					isChange = true
	// 					continue
	// 				}
	// 			}
	// 			if isChange {
	// 				bids := strings.Join(bidArr, ",")
	// 				if err := models.Exec(`update mt_brand_classify set bid = ? where id = ?`, bids, id) {
	// 					beego.Debug(err)
	// 					json["status"] = "0"
	// 					return
	// 				}
	// 			}
	// 		}
	// 	}
	// }
	if _, err := models.Save("mt_area_production", input); err != nil {
		beego.Debug(err)
		json["status"] = "0"
	} else {
		json["status"] = "1"
	}
}

type ShopContent struct {
	BaseController
}

func (c *ShopContent) Get() {
	id := c.GetString("id")
	if id != "" {
		info := models.Query(`select a.*,b.pathname,c.monicker,d.pathname as gzhpath,e.pathname as apppath,f.pathname as webpath,g.pathname as xapppath
		 from mt_shop a left join mt_resources b on a.logo=b.id left join mt_member c on a.uid=c.id left join mt_resources d on a.gzhimg=d.id 
		  left join mt_resources e on a.appimg=e.id left join mt_resources f on a.webimg=f.id left join mt_resources g on a.xappimg=g.id where a.id=` + id)
		for _, v := range info {
			t := fmt.Sprint(v["type"])
			t = strings.Trim(t, ",")
			if t == "" || t == "<nil>" {
				t = "''"
			}
			v["types"] = models.Query(fmt.Sprintf(`select name from mt_column where id in(%v)`, t))
			beego.Debug(v["types"])
			imgs := fmt.Sprint(v["imgs"])
			if imgs == "" || imgs == "<nil>" {
				imgs = "''"
			}
			v["companyimgs"] = models.Query(fmt.Sprintf(`select pathname from mt_resources where id in(%v)`, imgs))
		}
		c.Data["info"] = info[0]
		c.TplName = "admin/shop/content.html"
	} else {
		c.Ctx.Redirect(302, "/admin/shop/index")
	}
}

type ShopApply struct {
	BaseController
}

func (c *ShopApply) Get() {
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	lt := ` limit ` + page + `,` + num
	ob := ` order by a.addtime desc`
	sql := `select a.*,c.pathname,b.monicker from mt_shop_add a left join mt_member b on a.uid=b.id left join mt_resources c on b.avatar=c.id` + ob + lt
	sql2 := `select count(a.id) as totals from mt_shop_add a`
	info := models.Query(sql)
	for _, v := range info {
		v["types"] = models.Query(fmt.Sprintf(`select name from mt_column where id in(%v)`, v["type"]))
	}
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/shop/apply?`
	c.TplName = "admin/shop/apply.html"
}

type ShopApplyDetail struct {
	BaseController
}

func (c *ShopApplyDetail) Get() {
	id := c.GetString("id")
	if id != "" {
		info := models.Query(`select a.*,b.monicker,c.pathname,d.pathname as lpath,e.pathname as cpath,
			f.pathname as tpath,p.name as shen,o.name as shi,i.name as qu,g.pathname as logopath 
			from mt_shop_add a 
			left join mt_member b on a.uid=b.id 
			left join mt_resources c on b.avatar=c.id 
			left join mt_resources d on a.license=d.id 
			left join mt_resources e on a.cardimg=e.id 
			left join mt_resources f on a.theimg=f.id 
			left join mt_area p on a.province=p.id 
			left join mt_area o on a.city=o.id 
			left join mt_area i on a.area=i.id 
			left join mt_resources g on a.logo=g.id 
			where a.id=` + id)
		c.Data["info"] = info[0]
		c.TplName = "admin/shop/applyContent.html"
	} else {
		return
	}
}

type ShopApplyPush struct {
	BaseController
}

func (c *ShopApplyPush) Get() {
	id := c.GetString("id")
	content := c.GetString("content")
	mem := models.Query(`select b.wx_openid_gzh from mt_shop_add a left join mt_member b on a.uid=b.id where a.id=` + id)[0]
	if err := models.Exec(`update mt_shop_add set censoring=2 where id=` + id); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		data := map[string]map[string]interface{}{
			"first":    {"value": `您申请的店铺未通过`},
			"keyword1": {"value": `店铺`, "color": "#e4393c"},
			"keyword2": {"value": `原因:` + content, "color": "#9c9c9c"},
			"remark":   {"value": `您可以调整后再次审核`},
		}
		models.Push(mem["wx_openid_gzh"].(string), `o1pZ3qYLVc4jWU51MO5kio9gKOL1aV2hkrEHoVMU6Vc`, data, models.Urlc+"/mobile/my", "")
	}
	if fmt.Sprint(c.Data["json"]) == "1" {
		var r models.Mt_systems_record
		r.Tid, _ = strconv.Atoi(id)
		r.Way = 69
		r.Addtime = sword.Timeget()
		r.Table = 15
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
	c.ServeJSON()
}

type ShopApplyCensoring struct {
	BaseController
}

func (c *ShopApplyCensoring) Get() {
	id := c.GetString("id")
	mem := models.Query(`select b.wx_openid_gzh,b.mobile,b.password,b.avatar from mt_shop_add a left join mt_member b on a.uid=b.id where a.id=` + id)[0]
	if err := models.Exec(`update mt_shop_add set censoring=1 where id=` + id); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		data := map[string]map[string]interface{}{
			"first":    {"value": `您申请的店铺已通过`},
			"keyword1": {"value": `店铺`, "color": "#9c9c9c"},
			"keyword2": {"value": `通过`, "color": "#e4393c"},
			"remark":   {"value": `您可以管理您的店铺了~`},
		}
		models.Push(fmt.Sprint(mem["wx_openid_gzh"]), `o1pZ3qYLVc4jWU51MO5kio9gKOL1aV2hkrEHoVMU6Vc`, data, models.Urlc+"/mobile/my", "")
		apply := models.Query(`select * from mt_shop_add where id=` + id)[0]
		sql := fmt.Sprintf(`insert into mt_shop (uid,logo,name,person,tel,address,addtime,province,city,area,style) values ('%v','%v','%v','%v','%v',
			'%v','%v','%v','%v','%v',1)`, apply["uid"], apply["logo"], apply["name"], apply["person"], apply["tel"], apply["address"], sword.Gettimes(""),
			apply["province"], apply["city"], apply["area"])
		if ret, err := models.Orm().Raw(sql).Exec(); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
		} else {
			c.Data["json"] = 1
			sid, _ := ret.LastInsertId()
			sql2 := fmt.Sprintf(`insert into mt_systems_admin (accountnumber,password,permission,addtime,loginnumber,status,gid,avatar) 
				values ('%v','%v','%v','%v','0','1','%v','%v')`, mem["mobile"], mem["password"], 1, sword.Gettimes(""), sid, mem["avatar"])
			if err := models.Exec(sql2); err != nil {
				beego.Debug(err)
			}
		}
	}
	if fmt.Sprint(c.Data["json"]) == "1" {
		var r models.Mt_systems_record
		r.Tid, _ = strconv.Atoi(id)
		r.Way = 70
		r.Addtime = sword.Timeget()
		r.Table = 15
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
	c.ServeJSON()
}
